<template>
  <div class="book-detail-container">
    <!-- 图书基本信息 -->
    <div class="book-info">
      <div class="book-cover">
        <el-image :src="book.coverUrl" fit="contain" class="cover-image">
          <template #error>
            <div class="cover-error">暂无封面</div>
          </template>
        </el-image>
      </div>
      <!-- 图书基本信息 -->
      <div class="book-meta"> <!-- 修正类名拼写错误 -->
        <h2 class="book-title">{{ book.title }}</h2>
        <div class="meta-grid">
          <div class="meta-item">
            <i class="el-icon-user"></i>
            <span>{{ book.author }}</span>
          </div>
          <!-- 其他元数据项保持类似结构... -->
        </div>
        <el-button type="primary" class="borrow-btn" @click="openBorrowDialog">
          <i class="el-icon-reading"></i>
          立即借阅
        </el-button>
      </div>
    </div>

    <!-- 用户评价 -->
    <div class="user-reviews">
      <h3 class="section-title">
        <i class="el-icon-chat-line-round"></i>
        用户评价
      </h3>
      <div class="review-list">
        <el-card v-for="(review, index) in reviews" :key="index" class="review-card" shadow="hover">
          <!-- 评价内容... -->
        </el-card>
      </div>
    </div>



    <!-- 分步借阅弹窗 -->
    <el-dialog v-model="borrowDialogVisible" title="借阅流程" :width="dialogWidth">
      <div class="borrow-dialog-content">
        <!-- 步骤条 -->
        <el-steps :active="currentStep" finish-status="success" :simple="!isMobile" align-center>
          <el-step title="书籍信息" description="确认书籍信息"></el-step>
          <el-step title="选择借阅时长" description="选择借书和还书日期"></el-step>
          <el-step title="确认借阅信息" description="确认借阅信息"></el-step>
        </el-steps>

        <!-- 步骤内容 -->
        <div class="borrow-step">
          <div v-if="currentStep === 1">
            <h4>书籍信息</h4>
            <p><strong>书名：</strong>{{ book.title }}</p>
            <p><strong>作者：</strong>{{ book.author }}</p>
            <p><strong>ISBN：</strong>{{ book.isbn }}</p>
            <el-button type="success" @click="nextStep">下一步</el-button>
          </div>

          <div v-if="currentStep === 2">
            <h4>选择借阅时长</h4>
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="借书日期"
              end-placeholder="还书日期" value-format="YYYY-MM-DD" class="date-picker" />
            <el-button type="success" @click="nextStep">下一步</el-button>
          </div>

          <div v-if="currentStep === 3">
            <h4>确认借阅信息</h4>
            <p><strong>书名：</strong>{{ book.title }}</p>
            <p><strong>作者：</strong>{{ book.author }}</p>
            <p><strong>借书日期：</strong>{{ borrowDate }}</p>
            <p><strong>还书日期：</strong>{{ returnDate }}</p>
            <el-button type="success" @click="completeBorrow">完成借阅</el-button>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-skeleton :loading="isLoading" animated>
      <!-- 原有模板内容保持不变 -->
    </el-skeleton>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import api from "@/api";
import { useRoute, useRouter } from "vue-router";
import { useUserStore } from "@/stores/user"

const book = ref({
  title: "",
  author: "",
  publisher: "",
  publishDate: "",
  isbn: "",
  description: "",
  coverUrl: ""
});

const isLoading = ref(true);

const route = useRoute();
const router = useRouter();

const borrowDialogVisible = ref(false);
const currentStep = ref(1);
const borrowDate = ref(null);
const returnDate = ref(null);
const dateRange = ref([]); // 新增时间段绑定

const reviews = ref([]);


const isMobile = computed(() => window.innerWidth <= 768);
const dialogWidth = computed(() => (isMobile.value ? "90%" : "50%"));


// 获取图书详情
const fetchBookInfo = async () => {
  try {
    const res = await api.book.getBookInfo({ id: route.query.id });
    book.value = {
      ...res.data,
      coverUrl: res.data.coverUrl || require('@/assets/default_cover.png')
    };
  } catch (error) {
    console.log(error, "err")
    ElMessage.error("获取图书信息失败");
  } finally {
    isLoading.value = false;
  }
};

onMounted(fetchBookInfo);

const openBorrowDialog = () => {
  borrowDialogVisible.value = true;
  currentStep.value = 1;
};

const nextStep = () => {
  if (currentStep.value === 2) {
    if (!dateRange.value || dateRange.value.length !== 2) {
      ElMessage.error("请选择完整的借阅时间段");
      return; // 校验失败提前退出
    }
    [borrowDate.value, returnDate.value] = dateRange.value;
  }

  // 所有校验通过后统一推进步骤
  currentStep.value += 1;
};

const completeBorrow = async () => {
  try {
    // 获取用户信息
    const userStore = useUserStore()
    console.log(userStore)
    if (!userStore.library_users?.userId) {
      await router.push({ path: '/login', query: { redirect: route.fullPath } })
      return ElMessage.warning('请先登录')
    }

    // 参数校验
    if (!borrowDate.value || !returnDate.value) {
      return ElMessage.error('请选择完整的借阅时间段')
    }
    if (new Date(borrowDate.value) >= new Date(returnDate.value)) {
      return ElMessage.error('借书日期必须早于还书日期')
    }

    console.log(userStore.library_users.userId, route.query.id, borrowDate.value, returnDate.value)

    // 调用借阅接口
    const res = await api.book.createBorrow({
      userId: userStore.library_users.userId,
      bookId: route.query.id,
      borrowDate: borrowDate.value,
      returnDate: returnDate.value
    })

    if (res.code === 200) {
      ElMessage.success('借阅成功')
      borrowDialogVisible.value = false
    } else {
      ElMessage.error(res.message || '借阅失败')
    }
  } catch (error) {
    console.error('借阅出错:', error)
    ElMessage.error('借阅请求失败，请稍后重试')
  }
}
</script>

<style lang="scss" scoped>
.book-detail-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 30px;
  background: #ffffff;
  border-radius: 16px;
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.08);

  .book-info {
    display: grid;
    grid-template-columns: 280px 1fr;
    gap: 40px;
    margin-bottom: 40px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
      gap: 20px;
    }

    .book-cover {
      .cover-image {
        height: 400px;
        border-radius: 12px;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.02);
        }

        @media (max-width: 768px) {
          height: auto;
          max-height: 500px;
        }
      }
    }

    .book-meta {
      .book-title {
        font-size: 2.2rem;
        color: #2c3e50;
        margin-bottom: 25px;
        letter-spacing: -0.5px;
      }

      .meta-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
        margin-bottom: 30px;

        @media (max-width: 480px) {
          grid-template-columns: 1fr;
        }

        .meta-item {
          display: flex;
          align-items: center;
          padding: 12px 15px;
          background: #f8f9fa;
          border-radius: 8px;

          i {
            margin-right: 10px;
            font-size: 1.1rem;
            color: #409EFF;
          }

          span {
            font-size: 0.95rem;
            color: #4a5568;
          }
        }
      }

      .borrow-btn {
        padding: 14px 28px;
        font-size: 1.1rem;
        border-radius: 8px;
        transition: all 0.3s ease;

        i {
          margin-right: 8px;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 15px rgba(64, 158, 255, 0.3);
        }
      }
    }
  }

  .user-reviews {
    .section-title {
      font-size: 1.6rem;
      color: #2c3e50;
      margin-bottom: 25px;
      display: flex;
      align-items: center;

      i {
        margin-right: 10px;
        color: #67C23A;
      }
    }

    .review-list {
      display: grid;
      gap: 20px;

      .review-card {
        padding: 20px;
        border-radius: 12px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-3px);
        }

        p {
          margin: 8px 0;
          line-height: 1.7;
          color: #4a5568;
        }
      }
    }
  }

  // 移动端优化
  @media (max-width: 768px) {
    padding: 15px;
    margin: 10px;

    .book-info {
      .book-meta {
        .book-title {
          font-size: 1.8rem;
        }

        .meta-item {
          padding: 10px;
        }
      }
    }

    .el-dialog {
      :deep(.el-steps) {
        flex-direction: column;

        .el-step {
          margin-bottom: 15px;
        }
      }

      .date-picker {
        width: 100% !important;
      }

      .el-button {
        width: 100%;
        margin-top: 15px;
      }
    }
  }

  @media (max-width: 480px) {
    .borrow-btn {
      width: 100%;
    }
  }
}
